<template>
  <!-- 外部父使用 -->
     <!-- <div class="selectValue">
                        <positon-picker class="edit-form-item" label="位置经纬度" @confirm="addressConfirm"
                            :position="[formBaseData.longitude, formBaseData.latitude]" />
                    </div> -->
  <div>
    <slot name="input" :value-text="addressValue" :show-picker="showPicker">
      <van-field class="buildPageInput largeInput" :value="addressValue" :label="label" placeholder="" readonly
        :rules="rules" :is-link="!disabled" :required="required" @click="showPicker" />
    </slot>
    <van-popup v-model="show" position="bottom" :round="false" :style="{ height: '100vh' }">
      <div class="box">
        <div class="map" ref="map"></div>
        <div class="top_box" v-if="!disabled" style="position: absolute; top: 30px; left: 20px; right: 20px">
          <div class="input_box">
            <van-icon class="icon" name="search" size="14" />
            <input v-model="keyword" type="text" id="suggestId" placeholder="搜索地址">
            <van-icon @click="keyword = ''" class="right_icon" name="clear" size="14" v-if="keyword.length > 0" />
          </div>
          <div id="searchResult" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
        </div>
        <div class="bottom_box">
          <div class="addr_box">
            <div class="addr_title">我的位置</div>
            <div class="addr_content">
              <van-icon class="icon" name="location" />
              <span class="addr_text">{{ addr }}</span>
            </div>
          </div>
          <div class="button_box"><van-button round type="info" block @click="confirm">确定</van-button></div>
        </div>
        <div class="right_box">
          <div class="right_one" @click="changeZoom(1)"><van-icon name="plus" /></div>
          <div class="right_one" @click="changeZoom(-1)"><van-icon name="minus" /></div>
          <div class="right_one" @click="toLocation"><img src="@/assets/image/main/icon@2x.png" alt=""></div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant'
export const centerLng = 112.53;
export const centerLat = 32.99;
export default {
  name: 'positonPicker',
  props: {
    label: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    rules: {
      type: Array,
      default() {
        return []
      }
    },
    required: {
      type: Boolean,
      default: false
    },
    position: {
      type: Array,
      default: ['', '']
    }
  },
  watch: {
    position: {
      handler(position) {
        this.addressValue = `经度：${position[0] || '\t\t\t'}  纬度：${position[1] || '\t\t\t'}`
      },
      immediate:true
    }
  },
  data() {
    return {
      show: false,
      // formBaseData: {
      //   positionName: '',
      //   JD: '',
      //   WD: '',
      // },
      map: null,
      positionMask: [],
      Geolocation: null,
      Geocoder: null,
      addr: '',
      keyword: '',
      inputSearch: '',
      addressValue: ''
    }
  },
  methods: {
    showPicker() {
      if (!this.disabled) {
        this.show = true
        this.showGIS(this.position)
      }
    },
    clearMask() {
      this.positionMask.forEach(mask => {
        this.map.removeOverlay(mask)
        // mask.remove()
      })
    },
    setCenterMask(lng, lat, option) {
      this.clearMask()
      this.getBMap().then(BMap => {
        const point = new BMap.Point(lng, lat)
        const markerOption = {
          enableDragging: !this.disabled,
          raiseOnDrag: false
        }
        const mark = new BMap.Marker(point, markerOption)
        this.positionMask = [mark]
        this.map.addOverlay(mark)
        mark.addEventListener('dragend', this.getAddr)
        this.getAddr()
        if (option.setCenter) {
          // this.map.setViewport([point], { enableAnimation: true, margins: [100, 100, 500, 100] })
          this.map.panTo(point)
        }
      })
    },
    showGIS(position, callback) {
      this.show = true
      // this.clearMask()
      this.addr = ''
      // const option = {
      //   position: position,
      //   icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      //   anchor: 'bottom-center',
      //   cursor: 'pointer',
      //   zIndex: 100
      // }
      let lng, lat
      if (!position[0]) {
        lng = centerLng
        lat = centerLat
      } else {
        lng = position[0]
        lat = position[1]
      }
      const toast = Toast.loading({
        forbidClick: true,
        duration: 0
      })
      if (this.map === null) {
        this.$nextTick(() => {
          this.getBMap().then((BMap) => {
            this.map = new BMap.Map(this.$refs.map, { enableHighResolution: true })
            this.map.enableScrollWheelZoom()
            const point = new BMap.Point(lng, lat)
            this.map.centerAndZoom(point, 15)
            this.map.disableDoubleClickZoom()
            this.setCenterMask(lng, lat, { setCenter: true })
            if (this.keyword) {
            }
            if (!this.disabled) {
              // 单击选点
              // this.map.

              this.map.addEventListener('click', (e) => {
                this.setCenterMask(e.point.lng, e.point.lat, { setCenter: false })
                // alert(e.point.lng + ", " + e.point.lat)
              })
              // 顶部搜索
              if (this.ac) {
                this.ac.dispose()
                this.ac = null
              }
              let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                {
                  "input": "suggestId",
                }
              )
              this.ac = ac
              function G(id) {
                return document.getElementById(id);
              }
              ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                var str = "";
                var _value = e.fromitem.value;
                var value = "";
                if (e.fromitem.index > -1) {
                  value = _value.province + _value.city + _value.district + _value.street + _value.business;
                }
                str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                value = "";
                if (e.toitem.index > -1) {
                  _value = e.toitem.value;
                  value = _value.province + _value.city + _value.district + _value.street + _value.business;
                }
                str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                G("searchResult").innerHTML = str;
                console.log('str', str)
              });

              var myValue;
              const th = this
              ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                var _value = e.item.value;
                e.item.value.business && (vm.keyword = e.item.value.business)
                myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                console.log('myValue', myValue)
                G("searchResult").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                setPlace();
                // th.keyword = ''
              });
              const vm = this
              function setPlace() {
                // map.clearOverlays();    //清除地图上所有覆盖物
                function myFun() {
                  var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                  vm.inputSearch = pp
                  console.log(pp)
                  vm.setCenterMask(pp.lng, pp.lat, { setCenter: true })
                }
                var local = new BMap.LocalSearch(vm.map, { //智能搜索
                  onSearchComplete: myFun
                });
                local.search(myValue);
              }
            }
          }).catch((e) => {
            console.log(e)
          }).finally(() => {
            setTimeout(toast.clear, 200)
          })
        })
      } else {
        setTimeout(() => {
          this.setCenterMask(lng, lat, { setCenter: true })
          toast.clear()
        }, 500)
      }
    },
    changeZoom(zoomType) {
      this.map.setZoom(this.map.getZoom() + zoomType)
    },
    async toLocation() {
      if (this.Geolocation === null) {
        await this.getBMap().then(BMap => {
          this.Geolocation = new BMap.Geolocation({
            enableHighAccuracy: true
          })
        })
      }
      const vm = this
      this.Geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          if (vm.disabled) {
            vm.map.panTo(new BMap.Point(r.point.lng, r.point.lat))
          } else {
            vm.setCenterMask(r.point.lng, r.point.lat, { setCenter: true })
          }
        }
        else {
          const status = Number(this.getStatus())
          switch (status) {
            case 6: {
              alert('ERR_PERMISSION_DENIED，没有权限，定位被拒绝')
              break
            }
            case 2: {
              alert('ERR_POSITION_UNAVAILABLE，定位不可用')
              break
            }
            case 8: {
              alert('ERR_POSITION_UNAVAILABLE，定位超时')
              break
            }
          }
          // alert('failed' + this.getStatus());
        }
      })
    },
    cancel() {
      this.show = false
    },
    confirm() {
      this.show = false
      const position = this.positionMask[0].getPosition()
      this.$emit('confirm', { lng: position.lng, lat: position.lat, addr: this.addr })
      this.addressValue = `经度：${position.lng || '\t\t\t'}  纬度：${position.lat || '\t\t\t'}`
      // this.$emit('input', `经度：${position.lng||'\t\t\t'}  纬度：${position.lat||'\t\t\t'}`)
      this.keyword = ''
    },
    getAddr() {
      if (this.Geocoder === null) {
        this.Geocoder = new BMap.Geocoder()
      }
      let geoCoder = this.Geocoder
      const point = this.positionMask[0].getPosition()
      geoCoder.getLocation(point, (res) => {
        const { address, surroundingPois } = res
        if (Array.isArray(surroundingPois) && surroundingPois.length > 0) {
          this.addr = surroundingPois[0].address + surroundingPois[0].title
        } else {
          this.addr = address
        }
      })
    },
    getAddrText(position) {
      return new Promise((resolve, reject) => {
        if (this.Geocoder === null) {
          this.getAMap().then(AMap => {
            AMap.plugin('AMap.Geocoder', () => {
              this.Geocoder = new AMap.Geocoder()
              this.Geocoder.getAddress(position, (status, result) => {
                if (status === 'complete') {
                  resolve({ status, data: result })
                } else {
                  reject(result.message)
                }
              })
            })
          }).catch((err) => {
            reject(err)
          })
        } else {
          this.Geocoder.getAddress(position, (status, result) => {
            if (status === 'complete') {
              resolve({ status, data: result })
            } else {
              reject(result.message)
            }
          })
        }
      })
    },
    getBMap() {
      return new Promise((resolve, reject) => {
        resolve(window.BMap)
      })
    }
  },
}
</script>


<style scoped lang="scss">
.box {
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;

  .map {
    width: 100vw;
    height: inherit;
  }

  .right_box {
    position: absolute;
    right: 15px;
    bottom: 530px;
    z-index: 200;

    .right_one {
      width: 54px;
      height: 54px;
      background-color: #FFF;
      color: #4594F0;
      box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.08);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 2px;

      &:nth-child(2) {
        margin-bottom: 22px;
      }

      &:last-child {
        margin-bottom: 0;
      }

      >img {
        width: 38px;
        height: 38px;
      }
    }
  }

  .bottom_box {
    padding-top: 20px;
    background-color: #FFF;
    position: absolute;
    left: 15px;
    right: 15px;
    bottom: 136px;
    box-shadow: 0 0 12px 2px rgba(0, 0, 0, 0.14);
    border-radius: 24px;
    z-index: 200;

    .button_box {
      margin: 40px 192px 40px;

      ::v-deep .van-button {
        height: 74px;
      }
    }

    .addr_box {
      background: #F8F9FA;
      border-radius: inherit;
      margin: 0 16px;
      padding: 18px 0 24px;

      .addr_title {
        font-size: 34px;
        color: #222;
        text-align: left;
        padding-left: 32px;
        margin-bottom: 20px;
      }

      .addr_content {
        padding-left: 32px;
        text-align: left;

        .icon {
          color: #448EF7
        }

        .addr_text {
          font-size: 26px;
          color: #656668;
          font-weight: 400;
        }
      }
    }
  }
}

.top_box {
  border-radius: 36px;
  box-shadow: 0 6px 12px 2px rgba(0, 0, 0, 0.16);
  background-color: #FFF;
}

.input_box {
  display: flex;
  align-items: center;

  .icon {
    position: absolute;
    left: 34px;
    top: 50%;
    transform: translateY(-50%);
  }

  .right_icon {
    color: #E6E6E6;
    position: absolute;
    right: 34px;
    top: 50%;
    transform: translateY(-50%);
  }
}

#suggestId {
  box-sizing: border-box;
  padding-left: 78px;
  flex: 1 1 0;
  border: none;
  outline: none;
  height: 72px;
  border-radius: 36px;
}</style>

